class Furniture < ActiveRecord::Base
  
  validates :furniture_style_id,
    :material_id,
    :presence => true
    
  belongs_to :furniture_style
  belongs_to :material
  belongs_to :dept
  has_many :furniture_logistic_stats
  has_many :furniture_event_items
  
  scope :by_dept_id, lambda {|dept_id| where(:dept_id => dept_id) }
  scope :visible, where('status = ?','visible')

  def self.all_by_key_word(key_word)
    where('(materials.name like :key_word or materials.code like :key_word or factories.name like :key_word or furniture_styles.code like :key_word or furniture_styles.code like :key_word) ',{ :key_word => key_word}).includes(
      :material,
      :furniture_style => :factory      
    )
  end
  
  def full_name
    "#{furniture_style.code}-#{furniture_style.name}-#{material.code}-#{material.name}-#{spec}"
  end
  
  # 现货可预订数
  def spots_orderedable_count(args = { :order_item_id => 'none'})
    FurnitureLogisticStat.where('furniture_id = ?',id).each_with_object([]) do |stat,counts|
      counts << stat.spots_orderedable_count(args)
    end.sum
  end
  
  # 入库数或已预订数或售出数
  def entered_or_ordered_or_sold_count(request)
    FurnitureLogisticStat.where('furniture_id = ?',id).each_with_object([]) do |stat,counts|
      counts << stat.__send__(request) if stat.respond_to?(request)
    end.sum
  end

  # 库存数
  def stored_count
    FurnitureLogisticStat.where('furniture_id = ?',id).each_with_object([]) do |stat,counts|
      counts << (stat.entered_count - stat.sold_count)
    end.sum
  end

  # 现货预订数
  def orderedable_count(args = { :order_item_id => 'none'})
    if args[:order_item_id] == 'none' or args[:order_item_id].nil?
      stored_count - entered_or_ordered_or_sold_count("ordered_count")
    else
      logger.debug "order_item_id is #{args[:order_item_id]} #{stat_order_item_by_order_item_id(args[:order_item_id]).try(:ordered_count) || 0 } "
      stored_count - entered_or_ordered_or_sold_count("ordered_count") + (stat_order_item_by_order_item_id(args[:order_item_id]).try(:ordered_count) || 0)
    end
  end
end
